/*
Kakine
ActionScript Framework
Copyright © 2011, PUNY, LLC.

This file is part of KAKINE.

KAKINE is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

KAKINE is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with KAKINE.  If not, see <http://www.gnu.org/licenses/>.
*/ 
package com.puny.mvc.controllers
{
	import com.puny.mvc.controllers.Controller;
	import com.puny.mvc.helpers.DelayHelper;
	import com.puny.mvc.helpers.IHelper;
	import com.puny.mvc.views.View;
	import com.puny.utils.Random;

	public class SlideShowController extends Controller {
		private var _helper:IHelper;
		private var _bgs:Array;
		private var _interval:Number;
		private var _methodViewClass:Class
		
		/**
		 * Slide show controller
		 * @param arr array of asset instances
		 * @param cls view class
		 * @param interval miliseconds
		 * @param random if <code>true</code>, the first asset will be selected randomly. If <code>false</code>, the first asset in array will show up first.
		 * @see com.puny.mvc.views.slideshow.FadeOutView
		 */
		public function SlideShowController(arr:Array,cls:Class,interval:Number,random:Boolean=true) {
			_bgs = arr;
			_methodViewClass = cls;
			_interval = interval;
			if (random) {//shuffle
				shuffle();
			}
		}
		
		private function shuffle():void {
			for(var i:int = 0;i < Random.integer(_bgs.length);i++) {
				_bgs.push(_bgs.shift());
			}
		}
		
		private function putNewBG():void {
			var obj:* = _bgs.shift();
			addChildAt(new _methodViewClass(obj),0);
			_bgs.push(obj);
			if (numChildren > 1) {
				(getChildAt(1) as View).complete();
			}
			_helper = DelayHelper.setup(_interval,null,putNewBG);
		}
		
		override public function afterOpen():void {
			putNewBG();
			_helper.pause();
		}
		
		override public function pause():void {
			super.pause();
			_helper.pause();
		}
		
		override public function resume():void {
			super.resume();
			_helper.resume();
		}
		
		/**
		 * interval for each slide
		 * @param value milisecond
		 * 
		 */
		public function set interval(value:Number):void {
			_interval = value;
		}
		
		override public function afterClose():void {
			emptyArray(_bgs);
			_bgs = null;
			if(_helper != null) {
				_helper.skip();
			}	
		}
	}
}